package com.lenovo.testreport.test.server.api.service;

import com.lenovo.testreport.general.service.GeneralReportService;
import com.lenovo.testreport.test.server.api.mapper.TestServiceApiReportMapper;
import com.lenovo.testreport.test.server.api.model.TestServiceApiCaseWithBLOBs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ReportServiceImpl implements GeneralReportService {
    @Autowired
    TestServiceApiReportMapper mapper;
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Override
    public List findAllReport(String tablename) {

        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = tablename + "/AllReport/";
        redisTemplate.setKeySerializer(redisSerializer);
        List<TestServiceApiCaseWithBLOBs> List = (List<TestServiceApiCaseWithBLOBs>) redisTemplate.opsForValue().get(key);
        if (List == null) {
            List = mapper.selectAllReport(tablename);
            redisTemplate.opsForValue().set(key, List, 120, TimeUnit.SECONDS);
            //   System.out.println(key + " 缓存中没找到，访问数据库！");
        }// else System.out.println(key + " 缓存中找到了，无需访问数据库！");
        return List;

    }

    /**
     * 弃用
     *
     * @param tablename
     * @param type
     * @return
     */
    @Override
    public List<TestServiceApiCaseWithBLOBs> findByType(String tablename, String type) {
        return null;
    }

    @Override
    public List findReportByTime(String tablename, String start, String end, String version) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = tablename + "/From" + start + "to" + end + "/Version:" + version;
        redisTemplate.setKeySerializer(redisSerializer);
        List<TestServiceApiCaseWithBLOBs> List = (List<TestServiceApiCaseWithBLOBs>) redisTemplate.opsForValue().get(key);
        if (List == null) {
            List = mapper.selectAllReportByTime(tablename, start, end, version);
            redisTemplate.opsForValue().set(key, List, 120, TimeUnit.SECONDS);
        }
        return List;

    }

    @Override
    public List<String> findAllVersion(String tablename) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = tablename + "/AllVersion";
        redisTemplate.setKeySerializer(redisSerializer);
        List<String> List = (List<String>) redisTemplate.opsForValue().get(key);
        if (List == null) {
            List = mapper.selectAllVersion(tablename);
            redisTemplate.opsForValue().set(key, List, 120, TimeUnit.SECONDS);
        }
        return List;
    }
}
